﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using MesGLApp.DAL.RoleDB;
using MesGLApp.DAL.RoleDTO;
using MesGLApp.Tools;
using MesGLApp.View;
using LinqKit;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace MesGLApp.BLL.Role
{
    public class HomeControler : BaseControler
    {
        /// <summary>
        /// 查询系统信息
        /// </summary>
        /// <param name="progName"></param>
        /// <returns></returns>
        public BaseProgModel SearchProgInfoByName(string progName)
        {
            BaseProgModel resBean = null;
            using (RoleDB ctx = new RoleDB())
            {
                var query = ctx.base_prog.Where(p => p.prog_name.Equals(progName));
                if (query != null && query.Count() > 0)
                {
                    resBean = query.First();
                }
            }
            return resBean;
        }


        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="pwd">密码</param>
        /// <returns>用户实体类</returns>
        /// <exception cref="Exception"></exception>
        public BaseUserDTO Login(string userName, string pwd)
        {
            BaseUserDTO tmpBean = new BaseUserDTO();
            using (RoleDB ctx = new RoleDB())
            {
                var query = from a in ctx.base_user
                            join b in ctx.base_user_role on a.id equals b.base_user_id into tmp1
                            from ab in tmp1.DefaultIfEmpty()
                            join c in ctx.base_role on ab.base_role_id equals c.id into tmp2
                            from bc in tmp2.DefaultIfEmpty()
                            join d in ctx.base_dept on a.base_dept_id equals d.id into tmp3
                            from ad in tmp3.DefaultIfEmpty()
                            where a.user_name.Equals(userName)
                            select new { user = a, role = bc, dept = ad };
                if (query != null && query.Count() > 0)
                {
                    var item = query.First();
                    EntityTools.CopyEntity(item.user,ref tmpBean);
                    tmpBean.RoleModel = item.role ?? new BaseRoleModel();
                    tmpBean.deptModel = item.dept ?? new BaseDeptModel();
                    tmpBean.SexName = tmpBean.sex != null && tmpBean.sex == true ? "男" : "女";
                    if (tmpBean.is_del ?? false == true)
                    {
                        throw new Exception("该用户已经停用，不能登陆！");
                    }
                    else if (!tmpBean.pwd.Equals(pwd))
                    {
                        throw new Exception("用户与密码不符，请查正再拔！");
                    }
                    else
                    {
                        return tmpBean;
                    }
                }
                else 
                {
                    throw new Exception("没有找到相应的用户！");
                }
            }
        }


        /// <summary>
        /// 通过登陆用户查询用户的所有权限
        /// </summary>
        /// <param name="user">用户实体类</param>
        /// <returns>用户所有权限实体集合</returns>
        /// <exception cref="Exception">传入的用户实体为null时报错</exception>
        public List<BaseRoleModel> GetRoleInfoForUser(BaseUserModel user)
        {
            if (user != null)
            {
                var list = new List<BaseRoleModel>();
                using (RoleDB roleDB = new RoleDB())
                {
                    var query = from a in roleDB.base_user
                                where a.id == user.id
                                join b in roleDB.base_user_role on a.id equals b.base_user_id into res1
                                from ab in res1
                                join c in roleDB.base_role on ab.base_role_id equals c.id into res2
                                from bc in res2
                                select bc;

                    if (query != null && query.Count() > 0)
                    {
                        foreach (var item in query)
                        {
                            list.Add(item);
                        }
                    }
                }

                return list;
            }
            else
            {
                throw new Exception("传入的用户实体为空！");
            }
        }


        /// <summary>
        /// 通过多个角色取得权限树
        /// </summary>
        /// <param name="roleList">角色</param>
        /// <param name="prog">工程</param>
        /// <returns></returns>
        public List<BaseMenuDTO> GetMenuTreeForRole(List<BaseRoleModel> roleList, BaseProgModel prog)
        {
            List<BaseMenuDTO> resList = new List<BaseMenuDTO>();
            if (roleList != null && roleList.Count > 0)
            {
                using (RoleDB ctx = new RoleDB())
                {
                    //取得角色的ID
                    List<int> ids = roleList.Select(r => r.id).Distinct().ToList();

                    //查询语句
                    var query = from a in ctx.base_role
                                join b in ctx.base_role_menu on a.id equals b.base_role_id into res1
                                from ab in res1
                                join c in ctx.base_menu on ab.base_menu_id equals c.id into res2
                                from bc in res2
                                join d in ctx.base_prog on bc.base_prog_id equals d.id into res3
                                from cd in res3
                                where cd.id == prog.id && ids.Contains(a.id) && (bc.is_del ?? false) == false
                                select bc;
                    if (query != null && query.Count() > 0)
                    {
                        //将查询出来的界面做Distinct
                        List<BaseMenuModel> menuList = query.Distinct<BaseMenuModel>().ToList<BaseMenuModel>();

                        //取得最顶端的父节点
                        var parentQuery = menuList.Where(m => (m.parent_id ?? 0) == 0).OrderBy(m => m.sort);
                        if (parentQuery != null && parentQuery.Count() > 0)
                        {
                            int index = 101;
                            foreach (var parent in parentQuery)
                            {
                                BaseMenuDTO parentBean = new BaseMenuDTO();
                                Tools.EntityTools.CopyEntity<BaseMenuModel,BaseMenuDTO>(parent,ref parentBean);
                                //为父节点取得新的PageIndex(SunnyUI所用)
                                parentBean.PageIndex = index.ToString();
                                //递归查找父节点下面的子节点
                                this.SetChildMenu(parentBean, menuList);
                                resList.Add(parentBean);

                                index++;
                            }
                        }
                    }
                }
            }
            return resList;
        }

        public List<BaseMenuDTO> GetMenuTreeForRole(BaseRoleModel role,BaseProgModel prog)
        {
            if (role != null)
            {
                var list = new List<BaseMenuDTO>();
                using (RoleDB roleDB = new RoleDB())
                {
                    var query = from a in roleDB.base_role
                                join b in roleDB.base_role_menu on a.id equals b.base_role_id
                                join c in roleDB.base_menu on b.base_menu_id equals c.id
                                join d in roleDB.base_prog on c.base_prog_id equals d.id
                                where d.id == prog.id && a.id.Equals(role.id)
                                select c;
                    var ss = query.ToList();
                    if (query != null && query.Count() > 0)
                    {
                        var tmpQuery = query.Where(m => m.parent_id == null || m.parent_id == 0).OrderBy(m => m.sort);
                        var s = tmpQuery.ToList();
                        if (tmpQuery != null)
                        {
                            int index = 101;
                            foreach (var tmpItem in tmpQuery)
                            {
                                BaseMenuDTO menuDTO = new BaseMenuDTO();
                                menuDTO.PageIndex = index.ToString();
                                Tools.EntityTools.CopyEntity(tmpItem, ref menuDTO);
                                this.SetChildMenu(menuDTO, query.ToList<BaseMenuModel>());
                                list.Add(menuDTO);

                                index++;
                            }
                        }
                    }
                }
                return list;
            }
            else
            {
                throw new Exception("传入的角色实体为null!");
            }
        }

        private void SetChildMenu(BaseMenuDTO menu, List<BaseMenuModel> list)
        {
            if (menu != null)
            {
                if (list != null && list.Count() > 0)
                {
                    var query = list.Where(m => m.parent_id == menu.id).OrderBy(m => m.sort);
                    if (query != null && query.Count() > 0)
                    {
                        int index = 101;
                        menu.ChildMenu = new List<BaseMenuDTO>();
                        foreach (var tmpItem in query)
                        {
                            BaseMenuDTO childMenu = new BaseMenuDTO();
                            childMenu.PageIndex = menu.PageIndex.ToString() + index.ToString();
                            Tools.EntityTools.CopyEntity(tmpItem, ref childMenu);
                            menu.ChildMenu.Add(childMenu);
                            this.SetChildMenu(childMenu, list);

                            index++;
                        }
                    }
                }
            }
        }


    }
}
